/*
 * @Author: zhouwei wei.zhou@flip.fun
 * @Date: 2024-04-28 10:27:44
 * @LastEditors: zhouwei wei.zhou@flip.fun
 * @LastEditTime: 2024-04-28 11:55:01
 * @FilePath: /redux-tooltik/src/store/user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
const initialState = {
	number: 1,
}
// 创建一个异步的thunk
// 返回值是actions函数
export const addCountAsync = createAsyncThunk('add-count-async', async (state, action) => {
	console.log(state)
	const res = await new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve(state)
		}, 1000)
	})
	return res
})
/**
 * 创建一个分片store (可以理解为一个模块的store)
 * @returns   返回值是一个对象,其中包含了创建这个分片的reducer,以及触发的actions
 */
const user = createSlice({
	name: 'user',
	// 初始值
	initialState: initialState,
	reducers: {
		// reducers里的函数可以理解为触发修改的函数
		// 返回值
		add(state, action) {
			state.number += action.payload
		},
		subtract(state, action) {
			state.number -= action.payload
		},
	},
	extraReducers(builder) {
		builder.addCase(addCountAsync.fulfilled, (state, action) => {
			console.log(state)
			console.log(action.payload)
            state.number += action.payload
		})
	},
})
export const { add } = user.actions
export const getNumberSelector = store => store.user.number
export default user.reducer
